package com.xmx.productcenter.listener;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.rabbitmq.client.Channel;
import com.xmx.common.utils.R;
import com.xmx.productcenter.feign.OrderFeign;
import com.xmx.productcenter.service.GoodsProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

import static com.xmx.common.rabbitDto.OrderDto.STOCK_RELESE_QUEUE;

/**
 * 监听ttl队列
 */
@Slf4j
@Component
@RabbitListener(queues = {STOCK_RELESE_QUEUE})
public class StockListener {

    @Resource
    OrderFeign orderFeign;
    @Resource
    GoodsProductService goodsProductService;

    @RabbitHandler
    public void omMessage(Map map, Message messag , Channel channel) throws IOException {
        /**
         *        是否为第二次及以后派送过来的消息
         */
        Boolean redelivered = messag.getMessageProperties().getRedelivered();
        if(!redelivered) {
            log.error("收到的数据=============>>>{}", map);
            Integer orderId = (Integer) map.get("orderId");
            Integer prouductId = (Integer) map.get("prouductId");
            Integer prouductNum = (Integer) map.get("prouductNum");
            //查询订单状态
            R info = orderFeign.info(orderId);
            if (info.get("errno").equals(0)) {
//        Integer orderStatus = MapUtil.get((Map) info.get("order"), "orderStatus", Integer.class);
                Map order = (Map) info.get("order");

                if (order == null || order.get("orderStatus") == null) {
                    log.info("订单不存在，释放锁定库存======》》{}");
                    int i = goodsProductService.addStock(orderId, prouductId, prouductNum);
                    channel.basicAck(messag.getMessageProperties().getDeliveryTag(), false);
                } else if (order != null && (order.get("orderStatus").equals(102) || order.get("orderStatus").equals(103))) {
                    log.info("订单被取消或者被关闭，释放锁定库存======》》{}");
                    int i = goodsProductService.addStock(orderId, prouductId, prouductNum);
                    channel.basicAck(messag.getMessageProperties().getDeliveryTag(), false);

                }
            } else {
                log.info("库存释放处理======》》查询订单失败");
                channel.basicAck(messag.getMessageProperties().getDeliveryTag(), true);

            }
        }else {
            log.info("该库存消息已经被使用过了");
            channel.basicAck(messag.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
